package com.mininglamp.app.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.mininglamp.app.response.Response;
import com.mininglamp.app.util.ResponseHelper;

@Controller
@RequestMapping("/file")
public class FileController {

	private static final Logger log = LoggerFactory.getLogger(FileController.class);

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public Response upload(@RequestParam("file") MultipartFile file) throws IOException {
		log.info("{}", file);
		log.info("{}", file.getName());
		log.info("{}", file.getBytes().length);
		log.info("{}", file.getSize());
		log.info("{}", file.getOriginalFilename());

		return ResponseHelper.OK("upload ok");
	}

	@RequestMapping(value = "/download", method = RequestMethod.GET)
	public void downloadFile(HttpServletResponse response) throws UnsupportedEncodingException {
		response.setContentType("application/octet-stream");
		response.addHeader("Content-Disposition", "attachment;fileName=a.txt");
		byte[] buffer = "测试下载内容".getBytes("utf8");
		try {
			OutputStream os = response.getOutputStream();
			os.write(buffer, 0, buffer.length);
			log.info("download ok");
		} catch (Exception e) {
			log.error("download error", e);
		}
	}
	
	@RequestMapping(value = "/batch/upload", method = RequestMethod.POST)
    public String handleFileUpload(HttpServletRequest request) {
		MultipartHttpServletRequest multiRequest = ((MultipartHttpServletRequest) request);
        List<MultipartFile> files = multiRequest.getFiles("file");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(
                            new File(file.getOriginalFilename())));
                    stream.write(bytes);
                    stream.close();

                } catch (Exception e) {
                    stream = null;
                    return "You failed to upload " + i + " => "
                            + e.getMessage();
                }
            } else {
                return "You failed to upload " + i
                        + " because the file was empty.";
            }
        }
        return "upload successful";
    }

}
